iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
Vue.js

Vue 新手學習紀錄系列 第 24

Day 24 | v-model 雙向綁定

  • 分享至 

  • xImage
  •  

之前有寫道 props 和 emits 父元件和子元件相互傳資料的方式,那 v-model 是把這兩個東西包起來的語法,可以用 v-model 同時完成資料的傳入 (props) 和回傳 (emit)。

兩種寫法比較

原本 props/emit 的寫法

<!-- 父元件 -->
<ChildInput :modelValue="keyword" @update:modelValue="keyword = $event" />

<!-- 子元件 ChildInput.vue -->
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <input 
    :value="modelValue"
    @input="emit('update:modelValue', $event.target.value)"
  />
</template>

v-model 寫法

<!-- 父元件 -->
<ChildInput v-model="keyword" />
<!-- 子元件 ChildInput.vue -->
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <input 
    :value="modelValue"
    @input="emit('update:modelValue', $event.target.value)"
  />
</template>

v-model="keyword" 實際做的事情

  • 實際執行的 props: modelValue
  • 實際觸發的 emit: update:modelValue

綁定多個 v-model

假設實作一個有兩個輸入框的元件
子元件

<template>
  <div>
    <input :value="title" @input="emit('update:title', $event.target.value)" placeholder="標題" />
    <textarea :value="content" @input="emit('update:content', $event.target.value)" placeholder="內容"></textarea>
  </div>
</template>

<script setup>
const props = defineProps({
  title: String,
  content: String
})
const emit = defineEmits(['update:title', 'update:content'])
</script>

父元件

<PostEditor v-model:title="postTitle" v-model:content="postContent" />

小結

  • v-model 基本用法
  • 同時綁定多個 v-model

上一篇
Day 25|Vue Transition
系列文
Vue 新手學習紀錄24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言